package com.axonactive.yolo.service.implement;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.axonactive.yolo.dao.interfaces.ExchangeRateRepository;
import com.axonactive.yolo.domain.ExchangeRate;
import com.axonactive.yolo.exception.ExchangeRateNotFoundException;
import com.axonactive.yolo.service.interfaces.ExchangeRateService;

@Service
public class ExchangeRateServiceImpl implements ExchangeRateService {

	@Resource
	private ExchangeRateRepository exchangeRateRepository;

	@Override
	@Transactional
//	@CacheEvict(value = "listExchangeRateCache", allEntries = true)
	public List<ExchangeRate> findAll() {
		return exchangeRateRepository.findAll();
	}

	@Override
	@Transactional
//	@Cacheable(value = "exchangeRateByCodeCache", key = "#code")
	public ExchangeRate findByCode(String code) {
		return exchangeRateRepository.findByCode(code).get(0);
	}

	@Override
	@Transactional
//	@Cacheable(value = "listExchangeRateCache", key = "")
	public List<ExchangeRate> getRateListByBaseCurrency(
			ExchangeRate baseCurrency) {
		List<ExchangeRate> list = exchangeRateRepository
				.findByCodeNotLikeOrderByCodeAsc(baseCurrency.getCode());
		for (ExchangeRate er : list) {
			er.setRate(er.getRate() / baseCurrency.getRate());
		}
		return list;
	}

	@Override
	@Transactional(rollbackFor = ExchangeRateNotFoundException.class)
	public ExchangeRate update(String code, double rate)
			throws ExchangeRateNotFoundException {
		ExchangeRate er = findByCode(code);

		if (er == null) {
			throw new ExchangeRateNotFoundException("Exchange rate (code = "
					+ code + ") is not found");
		}

		er.setRate(rate);
		exchangeRateRepository.save(er);
		return er;
	}

	@Override
	@Transactional
	public double convert(double price, String oldCode, String newCode) {
		double rate = findByCode(newCode).getRate()
				/ findByCode(oldCode).getRate();
		double newPrice = price * rate;
		return newPrice;
	}

	@Override
	@Transactional
	public double getRateByNewCode(String newCode) {
		return findByCode(newCode).getRate();
	}

	@Override
	@Transactional
	public double getRateByOldCode(String oldCode) {
		return findByCode(oldCode).getRate();
	}

}
